﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes.CheckManagement
{
    public partial class ProcessSelectForm : DevExpress.XtraEditors.XtraForm
    {
        // --- 私有字段，用于分页和查询 ---
        private int currentPage = 1;
        private int pageSize = 3; // 你可以根据需要调整每页显示数量
        private int totalRecords = 0;

        // --- 公共属性，用于向父窗口返回选定的值 ---
        public string SelectedProcessId { get; private set; }
        public string SelectedProcessName { get; private set; }

        public ProcessSelectForm()
        {
            InitializeComponent();
            // --- 绑定所有事件 ---
            this.Load += ProcessSelectForm_Load;
            btnSearch.Click += btnSearch_Click;
            btnReset.Click += btnReset_Click;
            btnSubmit.Click += btnSubmit_Click;
            btnCancel.Click += (s, e) => { this.Close(); };
            btnNext.Click += btnNext_Click;
            btnPrev.Click += btnPrev_Click;
            gridView1.DoubleClick += gridView1_DoubleClick;
        }

        /// <summary>
        /// 窗体加载时，自动查询第一页数据
        /// </summary>
        private async void ProcessSelectForm_Load(object sender, EventArgs e)
        {
            await LoadDataAsync();
        }

        /// <summary>
        /// 核心方法：从API异步获取数据并绑定到GridControl
        /// </summary>
        private async Task LoadDataAsync()
        {
            // 从输入框获取查询条件
            var codeQuery = txtProcessCode.Text.Trim();
            var nameQuery = txtProcessName.Text.Trim();

            // 构造带查询参数的URL
            var queryBuilder = new StringBuilder($"http://localhost:5053/api/ProcessManagement/GetProcessStepUpList?PageIndex={currentPage}&PageSize={pageSize}");
            if (!string.IsNullOrEmpty(codeQuery))
            {
                queryBuilder.Append($"&ProcessCode={Uri.EscapeDataString(codeQuery)}");
            }
            if (!string.IsNullOrEmpty(nameQuery))
            {
                queryBuilder.Append($"&ProcessName={Uri.EscapeDataString(nameQuery)}");
            }

            var apiUrl = queryBuilder.ToString();

            using (var client = new HttpClient())
            {
                try
                {
                    var apiResponse = await client.GetFromJsonAsync<ProcessApiResponse>(apiUrl);
                    if (apiResponse != null && apiResponse.code == 200)
                    {
                        gridControl1.DataSource = apiResponse.items;
                        totalRecords = apiResponse.total;
                        currentPage = apiResponse.pageIndex;
                        pageSize = apiResponse.pageSize;
                        UpdatePaginationControls();

                        // --- 新增代码: 取消默认选中(焦点)第一行 ---
                        // 这样用户就必须手动选择，否则提交时会提示
                        if (apiResponse.items.Count > 0)
                        {
                            gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.InvalidRowHandle;
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("获取数据失败: " + apiResponse?.message);
                        gridControl1.DataSource = null; // 清空数据
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show("请求API时发生错误: " + ex.Message);
                }
            }
        }

        /// <summary>
        /// 更新分页按钮（上一页/下一页）和标签的状态
        /// </summary>
        private void UpdatePaginationControls()
        {
            int totalPages = (int)Math.Ceiling((double)totalRecords / pageSize);
            totalPages = totalPages > 0 ? totalPages : 1;
            lblPageInfo.Text = $"共 {totalRecords} 条，第 {currentPage}/{totalPages} 页";
            btnPrev.Enabled = currentPage > 1;
            btnNext.Enabled = currentPage < totalPages;
        }

        #region 事件处理
        private async void btnSearch_Click(object sender, EventArgs e)
        {
            currentPage = 1; // 每次查询都回到第一页
            await LoadDataAsync();
        }

        private async void btnReset_Click(object sender, EventArgs e)
        {
            txtProcessCode.Text = "";
            txtProcessName.Text = "";
            currentPage = 1;
            await LoadDataAsync();
        }

        private async void btnNext_Click(object sender, EventArgs e)
        {
            currentPage++;
            await LoadDataAsync();
        }

        private async void btnPrev_Click(object sender, EventArgs e)
        {
            currentPage--;
            await LoadDataAsync();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            SelectAndClose();
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            SelectAndClose(); // 双击行等同于点击"提交"按钮
        }
        #endregion

        /// <summary>
        /// 获取选中行的数据，赋值并关闭窗口
        /// </summary>
        private void SelectAndClose()
        {
            var selectedRow = gridView1.GetFocusedRow() as ProcessItem;
            if (selectedRow != null)
            {
                SelectedProcessId = selectedRow.processCode;
                SelectedProcessName = selectedRow.processName;
                this.DialogResult = DialogResult.OK; // 设置对话框结果为OK
                this.Close();
            }
            else
            {
                XtraMessageBox.Show("请先选择一道工序。");
            }
        }

        #region API数据模型
        public class ProcessItem
        {
            public long id { get; set; }
            public string processCode { get; set; }
            public string processName { get; set; }
            public bool isEnabled { get; set; }
            public string remark { get; set; } // 备注字段
        }

        public class ProcessApiResponse
        {
            public int total { get; set; }
            public int pageIndex { get; set; }
            public int pageSize { get; set; }
            public List<ProcessItem> items { get; set; }
            public int code { get; set; }
            public string message { get; set; }
        }
        #endregion

        private void ProcessSelectForm_Load_1(object sender, EventArgs e)
        {

        }
    }
}